<script setup lang="ts">
import { Toast, type FieldRule, type FormInstance } from 'vant';
import { ref, onUnmounted, onMounted } from 'vue';
import { loginByPassword, getSMSCode, loginByCode } from '@/services/user';
import { useUserStore } from '@/stores/user';
import { useRouter, useRoute } from 'vue-router';

// 用户store实例
const userStore = useUserStore();
// 路由管理实例 router
const router = useRouter();
// 当前的路由实例
const route = useRoute();

// 页面数据
const mobile = ref('');
const password = ref('');
const smsCode = ref('');
// 页面状态数据
const isPwdLogin = ref(true);
const isShowPwd = ref(false);
const isAgree = ref(false);

// 表单校验规则
const mobileRules: FieldRule[] = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' },
];
const passwordRules: FieldRule[] = [
  { required: true, message: '请输入密码' },
  { pattern: /^\w{8,24}$/, message: '密码需8-24个字符' },
];
const codeRules = [
  { required: true, message: '请输入验证码' },
  { pattern: /^\d{6}$/, message: '验证码6个数字' },
];

// 登录事件处理函数
const login = async (values: {
  mobile: string;
  password: string;
  smsCode: string;
}) => {
  if (!isAgree.value) return Toast('请勾选我已同意');
  // 登录判断
  if (isPwdLogin.value) {
    // loginByPassword(values.mobile, values.password)
    //   .then((succ) => {
    //     console.log('登录成功=====>', succ);
    //   })
    //   .catch((err) => {
    //     console.log('登录失败=====>', err);
    //   });
    // const res = await loginByPassword(values.mobile, values.password);
    // // 登录成功过才走这里
    // console.log('登录成功 await=====>', res);

    try {
      const user = await loginByPassword(values.mobile, values.password);
      console.log('密码登录', user.account);
      userStore.setUser(user);
      // 登录成功之后要判断一下，当前url地址里有没有回跳url
      const query = route.query;
      // 登录成功
      if (query.returnURL) {
        router.push(query.returnURL as string);
      } else {
        // 默认
        router.push('/user');
      }
      Toast.success('登录成功');
    } catch (error) {
      console.log('页面捕获的 error', error);
    }
  } else {
    const user = await loginByCode(values.mobile, values.smsCode);
    console.log('验证码登录', user);
    userStore.setUser(user);
    Toast.success('登录成功');
  }
};

// 表单实例
const form = ref<FormInstance | null>(null);
// 倒计时相关数据
let timerId: number = 0;
const count = ref(0);
// 发送验证码事件处理函数
const sendSms = () => {
  if (count.value > 0) return;
  // 校验手机号，获得 vant form 组件库的实例
  form.value
    ?.validate('mobile')
    .then(async (succ) => {
      console.log('succ', succ);
      // 开始计时
      window.clearInterval(timerId);
      count.value = 5;
      timerId = window.setInterval(() => {
        count.value--;
        if (count.value <= 0) {
          window.clearInterval(timerId);
        }
      }, 1000);
      // 发送验证码
      const code = await getSMSCode(mobile.value, 'login');
      console.log('验证码', code);
    })
    .catch((err) => {
      console.log('err', err);
    });
};

// 生命周期函数
onUnmounted(() => {
  // 组件卸载时清理定时器
  window.clearInterval(timerId);
});

onMounted(() => {
  // 使用QQ第三方登录的SDK暴露的全局方法：QC。生成QQ登录按钮，目的得到跳转链接
  // QC.Login({
  //   btnId: 'qqLoginBtn',
  // });
});
</script>

<template>
  <div class="login">
    <!-- 导航 -->
    <CpNavBar
      title="登 录"
      rightText="注 册"
      @click-right="userStore.delUser()"
    />
    <!-- 登录方式 -->
    <div class="login-head">
      <span class="title">{{ isPwdLogin ? '密码登录' : '短信登录' }}</span>
      <a class="sms" href="javascript:;" @click="isPwdLogin = !isPwdLogin">
        <span>{{ isPwdLogin ? '短信登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 登录表单 -->
    <div class="login-form">
      <van-form autocomplete="off" @submit="login" ref="form">
        <van-field
          placeholder="请输入手机号"
          v-model="mobile"
          type="tel"
          name="mobile"
          :rules="mobileRules"
        ></van-field>
        <van-field
          v-if="isPwdLogin"
          placeholder="请输入密码"
          v-model="password"
          :type="isShowPwd ? 'text' : 'password'"
          name="password"
          :rules="passwordRules"
        >
          <template #button>
            <CpIcon
              :name="isShowPwd ? 'login-eye-on' : 'login-eye-off'"
              @click="isShowPwd = !isShowPwd"
            />
          </template>
        </van-field>
        <van-field
          v-else
          placeholder="请输入验证码"
          type="text"
          :rules="codeRules"
          name="smsCode"
          v-model="smsCode"
        >
          <template #button>
            <span
              class="btn-send"
              :class="{ disabled: count > 0 }"
              @click="sendSms"
              >{{ count > 0 ? count + 's后发送' : '发送验证码' }}</span
            >
          </template>
        </van-field>
        <div class="cp-cell">
          <van-checkbox v-model="isAgree">
            <span>我已同意</span>
            <a href="javascript:;">用户协议</a>
            <span>及</span>
            <a href="javascript:;">隐私条款</a>
          </van-checkbox>
        </div>
        <div class="cp-cell">
          <van-button block round type="primary" nativeType="submit"
            >登 录</van-button
          >
        </div>
        <div class="cp-cell">
          <a href="javascript:;">忘记密码？</a>
        </div>
      </van-form>
    </div>

    <!-- 第三方登录 -->
    <!-- <div id="qqLoginBtn"></div> -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <a
        class="icon"
        href="https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fconsult-patients.itheima.net%2Flogin%2Fcallback"
      >
        <img src="@/assets/qq.svg" alt="qq-icon" />
      </a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  .login-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30px;

    .title {
      font-weight: bold;
      font-size: 24px;
    }
    .sms {
      span {
        font-size: 16px;
      }
    }
  }

  // 登录表单
  .login-form {
    padding: 0 14px;
    .cp-cell {
      display: flex;
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      align-items: center;
      .van-checkbox {
        a {
          color: var(--cp-primary);
          margin: 0 6px;
        }
      }
    }
    .btn-send {
      color: var(--cp-primary);
      &.disabled {
        color: rgba(22, 194, 163, 0.5);
      }
    }
  }

  // 第三方登录
  .login-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
</style>
